const {v4: uuidv4} = require('uuid');
const createModel = require('../mongodb/createModel')
const {setArticleCommentCount, setUserCommentArticles} = require("../utils/comment");

// 评论/留言
const schema = {
    // 文章ID
    articleId: {type: String, required: true},
    // 评论唯一ID
    commentId: {type: String, require: true},
    // 回复的ID
    parentId: {type: String, default: ''},

    // 评论人ID 用户ID
    commentUserId: {type: String, require: true},
    // 评论内容
    content: {type: String, default: '', require: true},
    // 被回复人ID 用户ID
    parentUserId: {type: String, default: ''},

    // 创建时间
    createTime: {type: Date, default: Date.now}
}

const model = createModel('comments', schema);


/**
 * 评论 / 回复
 * 示例： articleId: '000-000-000'
 * 评论：A先生 参数 articleId content
 *
 * {
 *      articleId: '000-000-000',
 *      commentId: 'abc-abc-abc',
 *      parentId: '',
 *      commentUserId: 'A先生的ID',
 *      content: 'A先生的评论内容',
 *      parentUserId: '',
 *      createTime: '2020-00-00'
 * }
 * 回复：B女士 参数 articleId content parentId parentUserId
 * {
 *      articleId: '000-000-000',
 *      commentId: 'xyz-xyz-xyz',
 *      parentId: 'abc-abc-abc',
 *      commentUserId: 'B女士的ID',
 *      content: 'B女士的回复内容',
 *      parentUserId: 'A先生的ID',
 *      createTime: '2020-11-11'
 * }
 * @param params    传参
 * @returns {Promise<object>} 结果
 */
const handleAdd = (params) => {
    return new Promise((resolve, reject) => {
        delete params.createTime;
        params.commentId = uuidv4();
        params.commentUserId = params.userId;
        model.create(params, async (err, docs) => {
            if (!err) {
                await setUserCommentArticles(params).catch(error => reject(error))
                const addCommentResult = await setArticleCommentCount(params).catch(error => reject(error))
                resolve(addCommentResult);
            } else {
                reject({code: 0, data: null, msg: err.message});
            }
        })
    })
}

/**
 * 查询评论
 * @param params 传参 articleId
 * @returns {Promise<object>} 结果
 */
const handleList = (params) => {
    return new Promise((resolve, reject) => {
        const aggregate = [
            {
                $match: {
                    articleId: params.articleId
                },
            },
            {
                $lookup: {
                    from: 'users',
                    localField: 'commentUserId',
                    foreignField: 'id',
                    as: 'commentUserInfo'
                }
            },
            {
                $unwind: {
                    path: '$commentUserInfo',
                    preserveNullAndEmptyArrays: true
                },
            },
            {
                $lookup: {
                    from: 'users',
                    localField: 'parentUserId',
                    foreignField: 'id',
                    as: 'parentUserInfo'
                }
            },
            {
                $unwind: {
                    path: '$parentUserInfo',
                    preserveNullAndEmptyArrays: true
                },
            },
            {
                $project: {
                    _id: 0, __v: 0,
                    'commentUserInfo._id': 0, 'commentUserInfo.__v': 0,
                    'parentUserInfo._id': 0, 'parentUserInfo.__v': 0,
                }
            }
        ]
        model.aggregate(aggregate, (err, docs) => {
            if (!err) {
                resolve({code: 1, data: docs, msg: '查询成功'});
            } else {
                reject({code: 0, data: null, msg: err.message});
            }
        })
    })
}


module.exports = {model, handleAdd, handleList}
